const express = require("express");
const expressHandlebars = require("express-handlebars");
const app = express();
const path = require("path");
const i18next = require("i18next");
const fsBackend = require("i18next-fs-backend");
const { LanguageDetector } = require("i18next-http-middleware");
const i18nextMiddleware = require("i18next-http-middleware"); // 确保你在这里导入了i18nextMiddleware
const cookieParser = require("cookie-parser");
const { getDetail, getList } = require("./api/index");
// 初始化i18next
i18next
  .use(fsBackend)
  .use(LanguageDetector)
  .init({
    fallbackLng: "en",
    debug: true,
    detection: {
      order: ["querystring", "cookie"],
      caches: ["cookie"],
    },
    backend: {
      loadPath: path.join(__dirname, "locales", "{{lng}}", "{{ns}}.json"),
    },
  });

// 应用i18next中间件
app.use(i18nextMiddleware.handle(i18next)); // 注意这里使用了i18nextMiddleware.handle

// 配置 Handlebars view engine
app.engine(
  "hbs",
  expressHandlebars.engine({
    extname: ".hbs",
    defaultLayout: false,
    // defaultLayout: 'main', // 指定布局文件 /layouts
    partialsDir: path.join(__dirname, "views/partials/"),
  })
);

app.set("view engine", "handlebars"); // 确保这一行在定义路由之前

// 使用 cookieParser
app.use(cookieParser());
// 设置 static 文件夹作为静态文件夹
app.use(express.static(path.join(__dirname, "static")));

// 当访问 /articleList 时，重定向到 /articleList/1
app.get("/articleList", (req, res) => {
  res.redirect("/articleList/1");
});

// 文章列表页
app.get("/articleList/:index", async (req, res) => {
  console.log(req.headers.cookie);
  const language = req.cookies.language; // 直接从cookies对象中获取language的值
  const index = parseInt(req.params.index);
  console.log(index);
  const articleList = await getList(index, language);
  console.log(articleList);
  if (articleList) {
    res.render("articleList.hbs", {
      record: articleList.articleList,
      pageNum: articleList.pageNum,
    });
  } else {
    res.status(404).send("文章列表未找到");
  }
});

// 文章详情页
app.get("/article/:id", async (req, res) => {
  const language = req.cookies.language; // 直接从cookies对象中获取language的值
  const id = parseInt(req.params.id);
  const article = await getDetail(id, language);
  console.log(article);
  if (article) {
    res.render("article.hbs", { article });
  } else {
    res.status(404).send("文章未找到");
  }
});

// 语言切换
app.get("/change-lang/:lang", (req, res) => {
  const lang = req.params.lang;
  i18next.changeLanguage(lang, (err) => {
    if (err) {
      console.error("Error changing language:", err);
    } else {
      res.cookie("language", lang); // 保存语言偏好  language
      res.cookie("i18next", lang); // 保存语言偏好  i18next 实际是这个有效
      res.redirect("back"); // 返回前一页
    }
  });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, "0.0.0.0", () => {
  console.log(`Server is running on port ${PORT}`);
});
